<template>
  <div class="admin-login-page">
    <div class="login-container">
      <div class="login-box">
        <div class="login-header">
          <div class="logo-container">
            <img src="@/assets/images/logo-3.jpg" alt="Logo" class="logo">
          </div>
          <h2>物联网数据平台</h2>
          <p class="subtitle">管理员登录</p>
        </div>
        <el-form 
          :model="loginForm" 
          ref="loginFormRef"
          :rules="rules"
          class="login-form"
        >
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username"
              placeholder="请输入管理员账号"
              :prefix-icon="User"
              clearable
              @keyup.enter="handleLogin"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input 
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
              clearable
              @keyup.enter="handleLogin"
              size="large"
            />
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              :loading="loading" 
              @click="handleLogin" 
              class="login-button"
              size="large"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
        <div class="login-footer">
          <el-divider>
            <span class="divider-content">其他登录方式</span>
          </el-divider>
          <el-button 
            link 
            type="primary" 
            @click="goToUserLogin"
            class="user-login-link"
            :icon="User"
          >
            普通用户登录
          </el-button>
        </div>
      </div>
    </div>
    <div class="login-background"></div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import { useAuthStore } from '../store/authStore';

const router = useRouter();
const authStore = useAuthStore();
const loading = ref(false);
const loginFormRef = ref(null);

// 检查当前登录状态
onMounted(() => {
  const token = authStore.token;
  const role = authStore.userRole;
  
  // 如果已经登录，直接跳转到对应页面
  if (token && role === 'admin') {
    router.push('/admin/dashboard');
  } else {
    // 清除所有登录状态，确保重新登录
    authStore.logout();
  }
});

const loginForm = reactive({
  username: '',
  password: ''
});

const rules = {
  username: [
    { required: true, message: '请输入管理员账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  
  try {
    await loginFormRef.value.validate();
    loading.value = true;

    const response = await fetch('https://penglink.pcwxcn.top/api/admin/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        name: loginForm.username.trim(),
        password: loginForm.password
      })
    });

    if (!response.ok) {
      throw new Error('登录失败，请检查网络连接');
    }

    const result = await response.json();
    // console.log('Login response:', result);

    if (result.code === 200) {
      // 获取用户信息
      const infoResponse = await fetch('https://penglink.pcwxcn.top/api/admin/info', {
        headers: {
          'Authorization': `Bearer ${result.data.token}`,
          'Accept': 'application/json'
        }
      });

      if (!infoResponse.ok) {
        throw new Error('获取用户信息失败');
      }

      const userInfo = await infoResponse.json();
      // console.log('User info:', userInfo);

      if (userInfo.code === 200) {
        // 保存登录状态
        authStore.login({
          token: result.data.token,
          role: userInfo.data.role || 'admin',
          userInfo: {
            username: userInfo.data.name,
            nickname: userInfo.data.nickname,
            name: userInfo.data.name,
            id: userInfo.data.id,
            createTime: userInfo.data.createTime,
            remark: userInfo.data.remark,
            // 确保保存设备权限信息
            devices: userInfo.data.devices || [],
            role: userInfo.data.role || 'admin'
          }
        });

        ElMessage.success('登录成功');
        router.push('/user/dashboard');
      } else {
        throw new Error(userInfo.msg || '获取用户信息失败');
      }
    } else {
      throw new Error(result.msg || '登录失败，请检查用户名和密码');
    }
  } catch (error) {
    // console.error('登录失败:', error);
    ElMessage.error(error.message || '登录失败，请重试');
  } finally {
    loading.value = false;
  }
};

const goToUserLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.admin-login-page {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('@/assets/images/1.png') center/cover no-repeat;
  position: relative;
  overflow: hidden;
}

.login-container {
  width: 420px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  z-index: 1;
}

.login-box {
  padding: 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo-container {
  margin: 0 auto;
}

.logo {
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
  background: #fff;
  border-radius: 50%;
  padding: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.login-header h2 {
  margin: 0;
  font-size: 28px;
  color: #303133;
  font-weight: 600;
}

.subtitle {
  margin: 8px 0 0;
  color: #909399;
  font-size: 16px;
}

.login-form {
  margin-top: 30px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  border-radius: 8px;
}

.login-footer {
  margin-top: 30px;
  text-align: center;
}

.divider-content {
  font-size: 14px;
  color: #909399;
}

.user-login-link {
  margin-top: 15px;
  font-size: 14px;
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 10% 20%, rgba(216, 241, 230, 0.46) 0%, rgba(233, 226, 226, 0.28) 50.3%, rgba(163, 222, 249, 0.37) 100.2%);
  z-index: 0;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409EFF 0%, #007FFF 100%);
  border: none;
  transition: transform 0.2s;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

@media (max-width: 768px) {
  .login-container {
    width: 90%;
    max-width: 420px;
    padding: 30px 20px;
  }
}
</style>